package org.gjt.jclasslib.util;
import java.io.*;
import org.gjt.jclasslib.io.ClassFileWriter;
import org.gjt.jclasslib.structures.CPInfo;
import org.gjt.jclasslib.structures.ClassFile;
import org.gjt.jclasslib.structures.InvalidByteCodeException;
import org.gjt.jclasslib.structures.constants.ConstantUtf8Info;

/**
 * @author zhou.wu
 * @version v1.0
 * @package com.melon.lotus.utils
 * @description: 修改class 文件
 * @date 2020/4/3 3:12 PM
 * see https://github.com/ingokegel/jclasslib
 */
public class ModifyByteClass {


    public static void main(String[] args) throws IOException, InvalidByteCodeException {
        String filePath = "/Users/fuxinghua/desktop/Cat.class";
        FileInputStream fis = new FileInputStream(filePath);

        DataInput di = new DataInputStream(fis);
        ClassFile cf = new ClassFile();
        cf.read(di);
        CPInfo[] infos = cf.getConstantPool();

        int count = infos.length;
        for (int i = 0; i < count; i++) {
            if (infos[i] != null) {
                System.out.print(i);
                System.out.print(" = ");
                System.out.print(infos[i].getVerbose());
                System.out.print(" = ");
                System.out.println(infos[i].getTagVerbose());
                //这里是需要更改的地方 通过idea  jclasslib bytecode viewer 插件 or 客户端
                //找到对应的编号
                if (i == 341) {
                    ConstantUtf8Info uInfo = (ConstantUtf8Info) infos[i];
                    uInfo.setString("/Users/fuxinghua/data/appdatas/cat/");
                    infos[i] = uInfo;
                }
            }
        }
        cf.setConstantPool(infos);
        fis.close();
        File f = new File(filePath);
        ClassFileWriter.writeToFile(f, cf);
    }
}
